/*
 * Shell.cpp
 *
 *  Created on: May 11, 2012
 *      Author: pleun
 */

#include "Shell.h"

Shell::Shell() {
	list = new List();
	token = 0;
	command = 0;

}

Shell::~Shell() {
	delete list;
}

void Shell::parseInput() {

	token = nextToken(cin);

	while (token->getType() != Token::END) {

		if (token->getText() == "logout" || token->getText() == "exit") {
			break;
		}

		parseList();

		token = nextToken(cin);

	}

}

void Shell::parseList() {

	list->addNewPipeline();
	parsePipeline();
	if (token->getType() == Token::SEQUENCE) {
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parseList();
	}
	executeAll();
	delete list;
	list = new List();

}

void Shell::parsePipeline() {
	list->addNewCommandLineToPipeline();
	parseCommandline();
	if (token->getType() == Token::PIPE) {
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parsePipeline();
	}
}

void Shell::parseCommandline() {
	if (token->getType() == Token::WORD) {
		command = list->getPipeline()->getCommandline();
		command->addNewCommandText(token->getText());
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parseCommandline();

	} else if (token->getType() == Token::APPEND) {
		command = list->getPipeline()->getCommandline();
		command->addNewCommandText(">>");
		command->SetContainsAppend();
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parseCommandline();

	} else if (token->getType() == Token::OUTPUT) {
		command = list->getPipeline()->getCommandline();
		command->addNewCommandText(">");
		cout << "TOKEN IS OUTPUT" << endl;
		command->SetContainsOutput();
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parseCommandline();

	} else if (token->getType() == Token::INPUT) {
		command = list->getPipeline()->getCommandline();
		command->addNewCommandText("<");
		command->SetContainsInput();
		if (token->getType() != Token::EOL) {
			token = nextToken(cin);
		}
		parseCommandline();
	}

}

void Shell::executeAll() {
	//cout << "Alles executeren" << endl;
	list->executeAll();

}
